<template>
    <basic-container>
        <avue-crud v-model="form" v-bind="bindVal" :page.sync="page" :highlight-current-row="true" v-on="onEvent">
            <template slot="json" slot-scope="{ row }">
                <div v-if="getFiles(row)">
                    <div v-for="(item, index) in getFiles(row)" :key="index" style="margin-bottom: 5px">
                        <el-link class="margin_right_10" type="warning" @click.stop="handlePreview(item, index, row)">
                            {{ handleTitle(item.title) }}
                            <i v-if="(item.title || '').includes('http')" class="el-icon-view hover"
                                @click.stop="handlePdfView(row, index, item)" />
                            <i class="el-icon-close hover" @click.stop="handleDelete(row, index, item)" />
                        </el-link>
                        <el-button v-if="previewDocument" size="mini" class="download-file el-icon-download"
                            @click.stop="downloadFile(item, index, row)">
                            预览文书
                        </el-button>
                    </div>
                </div>
                <el-link type="primary" @click="handleAdd(row)">新建</el-link>
            </template>
            <template slot="url" slot-scope="{ row }">
                <el-link v-for="(item, index) in handleRowUrl(row)" :key="index" class="margin_right_10" type="primary"
                    @click.stop="handlePreviewPdf(item, index, row)">
                    {{ formatUrl(item) }}
                    <i class="el-icon-close hover" @click.stop="handleDeletePdf(row, index, item)" />
                </el-link>
            </template>
            <template slot="menu" slot-scope="{ type, size, row }">
                <!-- <span v-if="$route.path.includes('photo') || $route.path.includes('materials') "> -->
                <span v-if="$route.path.includes('photo')">
                    <!-- <el-button icon="el-icon-picture-outline" :size="size" :type="type" @click="createQRcode">二维码</el-button> -->
                    <!-- <el-popover placement="right" trigger="click">
                        <vue-qr :size="191" :margin="0" :auto-color="true" :dot-scale="1" :text="iframeSrc" />
                        <el-button slot="reference" icon="el-icon-picture-outline" :size="size" :type="type">二维码</el-button>
                    </el-popover>
                    <el-button icon="el-icon-picture-outline" :size="size" :type="type"
                        @click="; (dialogVisible = true), (currentRow = row)">生成照片模板</el-button> -->
                </span>
                <span v-else-if="$route.path.includes('video')">
                    <el-button icon="el-icon-picture-outline" :size="size" :type="type"
                        @click="handlePreview('', '', row, '16')">
                        时间轴
                    </el-button>
                </span>
                <span v-else-if="$route.path.includes('materials')">
                    <el-button icon="el-icon-picture-outline" :size="size" :type="type"
                        @click="handlePreview('', '', row, '17')">
                        时间轴
                    </el-button>
                </span>
            </template>

            <template slot="state" slot-scope="{ row }">
                <el-tag v-if="row.$state === '未归档'" type="danger" size="mini">{{ row.$state }}</el-tag>
                <el-tag v-else size="mini" type="primary">{{
                    row.$state
                }}</el-tag>
            </template>
            <template slot="archivesType" slot-scope="{ row }">
                <el-tag :type="typeArr[
                        ['简易程序', '一般程序', '轻微火灾'].indexOf(
                            row.$archivesType
                        )
                        ]
                        " size="mini">{{ row.$archivesType }}
                </el-tag>
            </template>
        </avue-crud>
        <el-dialog :visible.sync="dialogVisible" title="照片模板" :class="[
            'avue-dialog custume-dialog',
            { 'avue-dialog--top': !fullscreen },
            { 'avue-dialog--fullscreen': fullscreen }
        ]" :fullscreen="fullscreen" width="60%">
            <div id="view_warper" class="print_wrap">
                <div v-for="(item, index) in printData" :key="index">
                    <div class="title">火灾现场照片</div>
                    <div class="text_align_right font_size_24">
                        {{ item.form.serial }}
                    </div>
                    <div class="margin_top_10" flex="main:center">
                        <img class="img_wrap" :src="item.url" alt="" srcset="" />
                    </div>
                    <div style="margin-top: 40px">
                        <b>说明：</b>{{ item.form.description }}
                    </div>
                    <div style="
                            margin-top: 30px;
                            font-size: 18px;
                            font-weight: bold;
                        " flex="main:justify">
                        <span>拍摄时间:{{
                            parseTime(
                                item.form.creatTime,
                                '{y}年{m}月{d}日'
                            )
                        }}</span>
                        <span>拍摄方向：{{ item.form.direction }} </span>
                        <span>制作时间:{{
                            parseTime(item.form.editTime, '{y}年{m}月{d}日')
                        }}</span>
                        <span>审核人: {{ item.form.applyPerson || '--' }}</span>
                    </div>
                    <div style="
                            margin-top: 30px;
                            font-size: 18px;
                            font-weight: bold;
                        " flex="main:justify">
                        <span>拍摄人:{{ item.form.person }}</span>
                        <span>制作人:{{ item.form.creator }}<span /></span>
                    </div>
                    <div style="
                            height: 1px;
                            background: #dcdcdc;
                            margin: 50px 0;
                        " />
                </div>
                <el-empty v-if="!printData.length" description="无图片数据，请选择单个上传" />
            </div>
            <div class="avue-dialog__footer">
                <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
                <el-button v-print="printObj" size="mini" type="primary" :loading="btnLoading">打印</el-button>
            </div>
        </el-dialog>
        <H5Iframe ref="H5Iframe" v-model="iframeVisible" :dictId="mapKey || $route.query.dictId"
            :noticeId="currentRow.noticeId" :archivesId="currentRow.archivesId" :keyId="currentKeyId"
            :currentIndex="currentIndex" @message="receiveMessage" :pdfDownload="pdfDownload" :isEdit="isEdit" />
    </basic-container>
</template>

<script>
import iframeView from '@/components/iframeView'
import pdfView from '@/components/pdfView'
import VueQr from 'vue-qr'
import H5Iframe from '@/components/H5Iframe/H5Iframe.vue'
import { MODULE_DICTID, MODULE_ID } from '@/const/modules/index.js'
export default window.$crudCommon(
    {
        name: 'Notice',
        components: { pdfView, iframeView, VueQr, H5Iframe },
        data() {
            return {
                dialogVisible: false,
                dialogPdfViewVisible: false,
                fullscreen: true,
                btnLoading: false,
                pdfUrl: '',
                typeArr: ['success', 'primary', 'warning'],

                iframeVisible: false,
                currentRow: {
                    noticeId: ''
                },
                currentIndex: '',
                currentKeyId: 0,
                mapKey: '',
                printObj: {
                    id: 'view_warper',
                    popTitle: '', // 打印配置页上方的标题
                    extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
                    preview: false, // 是否启动预览模式，默认是false
                    previewTitle: '预览的标题', // 打印预览的标题
                    previewPrintBtnLabel: '预览结束，开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
                    zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
                    standard: '',
                    extarCss: ''
                },
                pdfDownload: false,
                isEdit: false
            }
        },
        deactivated() {
            this.iframeVisible = false
        },
        computed: {
            printData() {
                const jsonStr = this.currentRow.jsonStr
                if (!jsonStr) return []
                else {
                    const arr = JSON.parse(jsonStr)
                        .filter(item => item.isNoGroup)
                        .reduce((prev, curr) => {
                            return [...prev, ...curr.imgFileList]
                        }, [])
                    return arr
                }
            },
            formatRecord() {
                return row => {
                    return (
                        row.reInquirytorName +
                        '-' +
                        this.parseTime(
                            row.createTime,
                            '{y}年{m}月{d}日{h}时{i}分'
                        ) +
                        '.pdf'
                    )
                }
            },
            formatUrl() {
                return url => {
                    // console.log(url)
                    if (!url) return
                    const arr = url.split('/')
                    return arr[arr.length - 1]
                }
            },
            iframeSrc2() {
                // 1.现场公告,2.询问笔录 3：物品清单 4：勘验笔录 5：现场平面图 6：环境勘验 7：初步勘验  8：细项勘验  9：专项勘验  10：证据材料 11 损失清单
                const obj = {
                    1: 'add',
                    2: 'penrecord',
                    3: 'inventory',
                    4: 'inquest',
                    5: 'add',
                    6: 'add',
                    7: 'add',
                    8: 'add',
                    9: 'add',
                    10: 'loss',
                    11: 'add',
                    12: 'add',
                    13: 'add',
                    14: 'minorFire',
                    16: 'videolist'
                }

                return `${process.env.VUE_APP_H5_API}/${obj[this.mapKey || this.$route.query.dictId]}?token=${this.$store.getters.token}&noticeId=${this.currentRow.noticeId}&currentIndex=${this.currentIndex}&nickName=${this.$store.state.user.nickName}&pdfDownload=${this.pdfDownload}&isEdit=${this.isEdit}`
            },
            currentModule() {
                const currentDictId = this.$route.query.dictId;
                const currentModule = Object.entries(MODULE_DICTID).find(([key, value]) => value == currentDictId);
                const [moduleName,] = currentModule;
                const moduleId = MODULE_ID[currentDictId]
                return { moduleName, moduleId }
            },
            previewDocument() {
                const currentDictId = this.$route.query.dictId;
                const { note, extract, inquest, loss, accident } = MODULE_DICTID
                return [note, extract, inquest, loss, accident].includes(Number(currentDictId))
            }
        },
        methods: {
            listBefore(done) {
                this.params.moduleName = this.currentModule.moduleName
                done()
            },
            delBefore(row, done) {
                this.customKey = this.currentModule.moduleId + 's'
                row.moduleName = this.currentModule.moduleName
                done()
            },
            searchChangBefore(params) {
                console.log(params);
                this.params = Object.assign(this.params, params)
                delete this.params.createTime
                this.params.searchCreateTime = params.createTime && params.createTime.length > 0 ? params.createTime.toString() : null
            },
            receiveMessage(event) {
                const eventName = event.data
                if (eventName == 'cancel') {
                    this.iframeVisible = false
                    this.currentIndex = ''
                    this.mapKey = ''
                } else if (eventName == 'success') {
                    this.$message.success('操作成功')
                    this.getList()
                    this.iframeVisible = false
                    this.pdfDownload = false
                    this.isEdit = false
                    this.currentIndex = ''
                    this.mapKey = ''
                }
            },
            handleTitle(title) {
                title = title + ''
                if (title.includes('http')) {
                    return title.substring(title.lastIndexOf('/') + 1)
                } else return title
            },
            handleDelete(row, index, item) {
                this.$confirm('此操作将删除该记录, 是否继续?', item.title, {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(async () => {
                        let moduleId = this.currentModule.moduleId
                        let res = await this.api.delModule(item[moduleId], { moduleName: this.currentModule.moduleName })
                        res.code == 200 ? this.$message.success('删除成功') : this.$message.error(res.msg)
                        this.refreshChange()
                    })
                    .catch(() => { })
            },

            handleDeletePdf(row, index, item) {
                this.$confirm('此操作将删除该记录, 是否继续?', item.title, {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        const newRow = JSON.parse(JSON.stringify(row))
                        const arr = newRow.url.split(',')
                        arr.splice(index, 1)
                        newRow.url = arr.join()
                        newRow.handleType = 3
                        this.handleSaveData(newRow)
                    })
                    .catch(() => { })
            },
            downloadFile(item, index, row) {
                this.pdfDownload = true
                this.currentRow = row
                const key = `${this.currentModule.moduleId}`
                this.currentKeyId = item[key]
                this.$nextTick(() => {
                    this.openwindow(this.$refs.H5Iframe.iframeSrc, '预览文书')
                    this.pdfDownload = false
                })
            },
            handleFileDelete(row, index, item) {
                this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        const newRow = JSON.parse(JSON.stringify(row))
                        const arr = newRow.url.split(',')
                        arr.splice(index, 1)
                        newRow.url = arr.join(',')
                        newRow.handleType = 3
                        this.handleSaveData(newRow)
                    })
                    .catch(() => { })
            },
            getFiles(row) {
                let key = this.currentModule.moduleName + 'List'
                if (!row[key]) return []
                return row[key].filter(item => item.title)
            },
            handlePdfView(row, index, item) {
                this.pdfUrl = item.title
                this.dialogPdfViewVisible = true
            },
            handlePreview(item, index, row, mapKey) {
                console.log('handlePreview');
                const key = `${this.currentModule.moduleId}`
                this.currentRow = row
                this.currentIndex = index
                console.log(this.currentIndex);
                this.currentKeyId = item[key]
                this.mapKey = mapKey
                this.pdfDownload = false
                this.isEdit = true
                this.iframeVisible = true
            },
            handlePreviewPdf(item) {
                window.open(item)
            },
            handleRowUrl(row) {
                return row.url ? row.url.split(',') : []
            },
            handleAdd(row) {
                this.pdfDownload = false
                this.currentRow = row
                this.currentKeyId = 0
                this.iframeVisible = true
            },
            handleUrl(url) {
                return url.substring(url.lastIndexOf('/') + 1)
            },
            async handleSaveFile(done, obj, fileName) {
                this.$Print('#view_warper')
            },
            handleSaveData(data, done) {
                this.api[this.option.update || 'update'](data).then(
                    data => {
                        this.$message.success('保存成功')
                        this.getList()
                        done && done()
                        this.dialogVisible = false
                        this._index = undefined
                    }
                )
            }
        }
    },
    {
        name: 'archives/notice',
        data: 'rows'
    }
)
</script>
<style lang="scss" scoped>
.download-file {
    color: #001e9e;
}
</style>
